package chapter1;

import java.util.Arrays;

public class InsertionSort {
    public static void insertionSort(int[] arr){
        if (arr == null || arr.length<2){
            return;
        }

        for (int i = 1; i < arr.length; i++) {
            for (int j = i-1; j >=0 && arr[j]>arr[j+1] ; j--) {
                swap(arr,j,j+1);
            }
        }
    }

    public static void swap(int[] arr,int i,int j){
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }

    //对数器实现
    public static int[] generateRandomArray(int maxSize,int maxValue){
        //随机数组长度
        int[] arr = new int[(int)(Math.random()*(maxSize+1))];
        for (int i=0;i<arr.length;i++){
            arr[i] = (int)(Math.random()*(maxValue+1)) - (int)((maxValue*Math.random()));//得到负数
        }
        return arr;
    }
    //复制数组
    public static int[] copyArray(int[] arr){
        if (arr==null){
            return null;
        }
        int[] res = new int[arr.length];
        for (int i=0;i<arr.length;i++){
            res[i] = arr[i];
        }
        return res;
    }

    public static boolean isEqual(int[] arr1,int[] arr2){
        int i =0;
        for (; i < arr1.length ; i++) {
            if (arr1[i] != arr2[i]){
                return false;
            }
        }
        return true;
    }

    //开始测试
    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize,maxValue);
            int[] arr2 = copyArray(arr1);
            insertionSort(arr1);
            Arrays.sort(arr2);
            if (!isEqual(arr1,arr2)){
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "nice!":"Fucking");
    }
}
